package com.anda.logistics.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.anda.logistics.dao.SystemMenuDao;
import com.anda.logistics.model.SystemMenu;
import com.anda.logistics.model.SystemUser;

@Component
public class SystemMenuDaoImpl extends AndaBaseSuperDao implements SystemMenuDao {
	
	@Override
	public void save(SystemMenu systemMenu) {
		sessionFactory.getCurrentSession().save(systemMenu);
	}

	@Override
	public List<SystemMenu> getAll() {
		return sessionFactory.getCurrentSession().createQuery("from SystemMenu order by sortNum, id").list();
	}
	
	@Override
	public SystemMenu getOne(long id){
		return (SystemMenu) sessionFactory.getCurrentSession().get(SystemMenu.class, id);
	}
	
	@Override
	public void deleteOne(long id){
		SystemMenu m = new SystemMenu(id);
		sessionFactory.getCurrentSession().delete(m);
	}

	@Override
	public void update(SystemMenu systemMenu) {
		sessionFactory.getCurrentSession().update(systemMenu);		
	}

	@Override
	public List<SystemMenu> getUserMenus(SystemUser user) {
		if (null == user) return null;
		StringBuffer sql = new StringBuffer()
			.append("select * from SystemMenu where id in ( ")
			.append("   select a.menuId from RoleMenuRights a , SystemUserRole b ")
			.append("    where a.roleId = b.roleId and a.accessRights = 1 ")
			.append("      and b.userId = :userId ) order by sortNum");
		return sessionFactory.getCurrentSession()
			.createSQLQuery(sql.toString())
			.addEntity(SystemMenu.class)
			.setLong("userId", user.getId())
			.list();
	}
	
}
